package com.facebook.presto.tdengine;

import com.facebook.presto.common.type.Type;
import com.facebook.presto.spi.RecordCursor;
import com.google.common.base.Strings;
import io.airlift.slice.Slice;

import java.util.Iterator;
import java.util.List;

public class TdEngineRecordCursor implements RecordCursor {

    private List<TdEngineColumnHandle> columnHandles;
    private Iterator<TdEngineRow> iterator;
    private TdEngineRow row;

    public List<TdEngineColumnHandle> getColumnHandles() {
        return columnHandles;
    }

    public void setColumnHandles(List<TdEngineColumnHandle> columnHandles) {
        this.columnHandles = columnHandles;
    }

    public Iterator<TdEngineRow> getIterator() {
        return iterator;
    }

    public void setIterator(Iterator<TdEngineRow> iterator) {
        this.iterator = iterator;
    }

    public TdEngineRow getRow() {
        return row;
    }

    public void setRow(TdEngineRow row) {
        this.row = row;
    }

    public TdEngineRecordCursor(List<TdEngineColumnHandle> columnHandles, TdEngineSplit split) throws Exception {
        this.columnHandles = columnHandles;
        this.iterator = TdUtil.select(split.getTableName(), split.getSchemaName());
    }

    @Override
    public long getCompletedBytes() {
        return 0;
    }

    @Override
    public long getReadTimeNanos() {
        return 0;
    }

    @Override
    public Type getType(int field) {
        return columnHandles.get(field).getColumnType();
    }

    @Override
    public boolean advanceNextPosition() {
        //   log.debug("advanceNextPosition--------------------------");
        if (!iterator.hasNext()) {
            return false;
        }
        //  log.debug("advanceNextPosition-------------------------hasNext");
        this.row = iterator.next();
        return true;
    }

    @Override
    public boolean getBoolean(int field) {
        String columnName = columnHandles.get(field).getColumnName();
        return Boolean.parseBoolean(row.getColumnMap().get(columnName));
    }

    @Override
    public long getLong(int field) {
        String columnName = columnHandles.get(field).getColumnName();
        String value = row.getColumnMap().get(columnName);
        return Long.parseLong(value);
    }

    @Override
    public double getDouble(int field) {
        return 0;
    }

    @Override
    public Slice getSlice(int field) {
        return null;
    }

    @Override
    public Object getObject(int field) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isNull(int field) {
        String columnName = columnHandles.get(field).getColumnName();
        String value = row.getColumnMap().get(columnName);
        return Strings.isNullOrEmpty(value);
    }

    @Override
    public void close() {

    }
}
